package game;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author Lucas 'Mezmor' Pfister
 *
 */
public class TileMap implements Serializable {

	private static final long serialVersionUID = 8010773196240730841L;
	
	private String name;
	private Unit[][] units;
	private String[][] terrain;
	
	public TileMap(String name, Unit[][] units, String[][] terrain){
		validateDimensions(units, terrain);
		this.name = name;
		this.units = units;
		this.terrain = terrain;
	}
	
	public TileMap(String name) throws ClassNotFoundException, IOException{
		TileMap newMap = deserialize(name);
		this.name = newMap.name;
		this.units = newMap.units;
		this.terrain = newMap.terrain;
	}
	
	public int getHeight(){ // Get number of rows
		return units.length; // Since int[rows][cols]
	}
	
	public int getWidth(){ // Get number of columns
		return units[0].length; // Since int[rows][cols]
	}
	
	public String getName(){
		return name;
	}
	
	public Unit[][] getUnits(){
		return units;
	}
	
	public String[][] getTerrain(){
		return terrain;
	}
	
	private void validateDimensions(Unit[][] units, String[][] terrain){
		if(units.length != terrain.length)
			throw new IllegalArgumentException("Unit row-size does not equal terrain row-size.");
		if(units[0].length != terrain[0].length)
			throw new IllegalArgumentException("Unit column-size does not equal terrain column-size.");
	}
	
	private TileMap deserialize(String name) throws ClassNotFoundException, IOException{
		if(name.contains(".ser")){
			FileInputStream fileIn = new FileInputStream(name);
			ObjectInputStream in = new ObjectInputStream(fileIn);
			TileMap returnMap = (TileMap) in.readObject();
			in.close();
			fileIn.close();
			
			return returnMap;
		}
			
		String fileName = "maps/";
		fileName += name;
		fileName += ".ser";
		FileInputStream fileIn = new FileInputStream(fileName);
		ObjectInputStream in = new ObjectInputStream(fileIn);
		TileMap returnMap = (TileMap) in.readObject();
		in.close();
		fileIn.close();
		
		return returnMap;
	}
	
	public void serialize() throws IOException {
		String fileName = "maps/";
		fileName += this.name;
		fileName += ".ser";
		FileOutputStream fileOut = new FileOutputStream(fileName);
		ObjectOutputStream out = new ObjectOutputStream(fileOut);
		out.writeObject(this);
		out.close();
		fileOut.close();
	}
}